﻿using UnityEngine;
using System.Runtime.InteropServices;
using System.Collections;
using UnityEngine.Networking;

public class CallJs : MonoBehaviour {
    [DllImport("__Internal")]
    private static extern void Hello();


    public void callJsHello() {
        Hello();
    }

    public void callJsGetImage() {
        GetImage.GetImageFromUserAsync(gameObject.name, "ReceiveImage");
    }

    static string s_dataUrlPrefix = "data:image/png;base64,";
    public void ReceiveImage(string dataUrl)
    {
        if (dataUrl.StartsWith(s_dataUrlPrefix))
        {
            Debug.Log("dataUrl:" + dataUrl);
            byte[] pngData = System.Convert.FromBase64String(dataUrl.Substring(s_dataUrlPrefix.Length));
            StartCoroutine(MakeUpload(pngData));
            Debug.Log("done upload");
        }
        else
        {
            Debug.LogError("Error getting image:" + dataUrl);
        }
    }


    public IEnumerator MakeUpload(byte[] imgData)
    {
        WWWForm form = new WWWForm();
        //form.AddBinaryData("file", System.IO.File.ReadAllBytes("1114.png"), "1114.png", "image/png");
        form.AddBinaryData("file", imgData, "image.png", "image/png");
        UnityWebRequest request = UnityWebRequest.Post("http://172.16.25.145:8080/api/performad/material/upload?type=0&advertiserId=128", form);
        //UnityWebRequest request = UnityWebRequest.Post("http://localhost:8082/api/performad/material/upload?type=0&advertiserId=128", form);
        request.SetRequestHeader("server-call", "adsapi");
        request.method = "POST";
        yield return request.SendWebRequest();
        print("request completed with code: " + request.responseCode);
        if (request.isHttpError)
        {
            print("Error: " + request.error);
        }
        else
        {
            print("Request Response: " + request.downloadHandler.text);
        }
    }
}